package com.dxy.lc.socketio.handler;

import com.dxy.lc.base.AppConstant;
import com.dxy.lc.enums.UserStatus;
import com.dxy.lc.model.bean.UserStateDto;
import com.dxy.lc.model.entity.User;
import com.dxy.lc.service.UserService;
import com.dxy.lc.socketio.ISession;
import com.dxy.lc.socketio.ISessionService;
import com.dxy.lc.socketio.OnDisconnectEventHandler;
import com.dxy.lc.utils.LoginUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class LcOnDisConnectEventHandler implements OnDisconnectEventHandler {

    @Autowired
    private ISessionService sessionService;
    @Autowired
    private UserService userService;

    @Override
    public void onDisconnect(ISession session) {
        if (session == null){
            return;
        }
        // 获取userId
        String token = session.getConnectParam(AppConstant.QUERY_TOKEN_KEY);
        String userId = LoginUtil.getUserId(token);

        // 更新用户状态
        User u = new User().setId(Integer.parseInt(userId)).setStatus(Integer.parseInt(UserStatus.OFFLINE.toCode()));
        userService.updById(u);

        // 广播所有用户下线状态
        UserStateDto usd = new UserStateDto()
                .setUserId(Integer.parseInt(userId))
                .setUserStatus(UserStatus.OFFLINE);
        sessionService.sendMessageToLoginUsers(AppConstant.SOCKET_EVENT_STATE, usd);
    }
}
